package cn.newgrand.netcall.offlinefiletransfer;

import java.awt.Color;

import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

import org.jivesoftware.resource.Res;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomClosingListener;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.spark.ui.TranscriptWindow;
import org.jivesoftware.spark.util.log.Log;
import cn.newgrand.netcall.offlinefiletransfer.OfflineReceiveMessage;
import cn.newgrand.smackx.packet.OfflineProxyPacket;

public class OfflineTransferManager {

    public static void handleTransferRequest(OfflineFileTransferRequest request) {
        // Check if a listener handled this request

        ContactList contactList = SparkManager.getWorkspace().getContactList();
        
        String requestor = request.getRequestor();
        String bareJID = StringUtils.parseBareAddress(requestor);
        String fileName = request.getFileName();


        ContactItem contactItem = contactList.getContactItemByJID(bareJID);

        ChatRoom chatRoom;
        if (contactItem != null) {
            chatRoom = SparkManager.getChatManager().createChatRoom(bareJID, contactItem.getDisplayName(), contactItem.getDisplayName());
        }
        else {
            chatRoom = SparkManager.getChatManager().createChatRoom(bareJID, bareJID, bareJID);
        }

        TranscriptWindow transcriptWindow = chatRoom.getTranscriptWindow();
        StyledDocument doc = (StyledDocument)transcriptWindow.getDocument();
        transcriptWindow.insertCustomText(Res.getString("message.file.transfer.chat.window"), true, false, Color.BLACK);
        
        // The image must first be wrapped in a style
        Style style = doc.addStyle("StyleName", null);

        final OfflineReceiveMessage receivingMessageUI = new OfflineReceiveMessage();
        receivingMessageUI.acceptFileTransfer(request);

        chatRoom.addClosingListener(new ChatRoomClosingListener() {
            public void closing() {
                receivingMessageUI.cancelTransfer();
            }
        });

        StyleConstants.setComponent(style, receivingMessageUI);

        // Insert the image at the end of the text
        try {
            doc.insertString(doc.getLength(), "ignored text", style);
            doc.insertString(doc.getLength(), "\n", null);
        }
        catch (BadLocationException e) {
            Log.error(e);
        }

        chatRoom.increaseUnreadMessageCount();

        chatRoom.scrollToBottom();
        
        String fileTransMsg = contactItem.getDisplayName() + " " + Res.getString("message.file.transfer.short.message") + " " + fileName;
        SparkManager.getChatManager().getChatContainer().fireNotifyOnMessage(chatRoom, true, fileTransMsg, Res.getString("message.file.transfer.notification"));
    }
    
    public static OfflineProxyPacket getOfflineFileInfo(){
    	OfflineProxyPacket iq = new OfflineProxyPacket();
    	iq.setTo("proxy."+SparkManager.getConnection().getServiceName());
    	iq.setFrom(SparkManager.getConnection().getUser());
    	iq.setType(Type.GET);
		PacketFilter filter = new PacketIDFilter(iq.getPacketID());
		PacketCollector collector = SparkManager.getConnection().createPacketCollector(filter);
		SparkManager.getConnection().sendPacket(iq);
		Packet packet = collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
		OfflineProxyPacket result = (OfflineProxyPacket)packet;
		return result;
    }
    public static void sendOfflineFilePacket(){
    	OfflineProxyPacket iq = new OfflineProxyPacket();
    	iq.setTo("proxy."+SparkManager.getConnection().getServiceName());
    	iq.setFrom(SparkManager.getConnection().getUser());
    	iq.setType(Type.GET);
		SparkManager.getConnection().sendPacket(iq);
    }
}
